//
//  UITextField+ZXHelper.m
//  Baby
//
//  Created by xielei on 15/12/20.
//  Copyright © 2015年 sina. All rights reserved.
//


#import "UITextField+ZXHelper.h"

@implementation UITextField (ZXHelper)


#pragma mark - 字符串的邮箱／手机号／URL／密码等验证

+ (BOOL)zx_validateEmail:(nullable NSString *)email
{
    if ([email rangeOfString:@"@"].length != 0 && [email rangeOfString:@"."].length !=0)
    {
        NSCharacterSet *tmpInvalidCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
        NSMutableCharacterSet *tmpInvalidMutableCharSet = [tmpInvalidCharSet mutableCopy];
        [tmpInvalidMutableCharSet removeCharactersInString:@"_-"];
        NSRange  range1 = [email rangeOfString:@"@" options:NSCaseInsensitiveSearch];
        //取得用户名部分
        NSString *userNameString = [email substringToIndex:range1.location];
        NSArray *userNameArray = [userNameString componentsSeparatedByString:@"."];
        for(NSString *str in userNameArray)
        {
            NSRange rangeOfInavlidChars = [str rangeOfCharacterFromSet:tmpInvalidMutableCharSet];
            if (rangeOfInavlidChars.length !=0 || [str isEqualToString:@""])
            {
                return NO;
            }
        }
        
        //取得域名部分
        NSString *domainString = [email substringFromIndex:range1.location+1];
        NSArray *domainArray = [domainString componentsSeparatedByString:@"."];
        for(NSString *string in domainArray)
        {
            NSRange rangeOfInavlidChars = [string rangeOfCharacterFromSet:tmpInvalidMutableCharSet];
            if (rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
            {
                return NO;
            }
        }
        return YES;
    }
    else
    {
        return NO;
    }
}


+ (BOOL)zx_validateEmail2:(nullable NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//这个手机号验证已经不符合最新的发展了,目前还有很多额外的号码段，所以最好放开，不要验证；
+ (BOOL)zx_validatePhoneNumber:(nullable NSString *)phone
{
    NSString *regexExp = @"^1[3|4|5|7|8][0-9]\\d{8}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexExp];
    return [emailTest evaluateWithObject:phone];
}

+ (BOOL)zx_validatePassword:(NSString *)pass
{ 
    NSString *regexExp = @"^[A-Za-z0-9]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexExp];
    return [emailTest evaluateWithObject:pass];
}

+ (BOOL)zx_validatePassword2WithOnlyLetterAndDigital:(NSString *)pass
{
    NSString *regexExp = @"[0-9]+[a-zA-Z]+[0-9a-zA-Z]*|[a-zA-Z]+[0-9]+[0-9a-zA-Z]*";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexExp];
    return [emailTest evaluateWithObject:pass];
}


+ (BOOL)zx_validatePassword3WithContainLetterAndDigital:(NSString *)pass
{
    NSCharacterSet *digitalSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    NSCharacterSet *letterSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];
    NSRange digitalRange = [pass rangeOfCharacterFromSet:digitalSet];
    NSRange letterRange = [pass rangeOfCharacterFromSet:letterSet options:NSCaseInsensitiveSearch];
    if ((digitalRange.location != NSNotFound) && (letterRange.location != NSNotFound))
    {
        return YES;
    }
    return NO;
}

#pragma mark - textField输入限制

+ (BOOL)zx_validateURL:(NSString *)url
{
    NSError *error;
    // 正则1
    NSString *regulaStr =@"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
    
//    // 正则2
//    regulaStr =@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                          options:NSRegularExpressionCaseInsensitive
                                                                            error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:url options:0 range:NSMakeRange(0,[url length])];
    if (arrayOfAllMatches.count >0) {
        return YES;
    }
//    for (NSTextCheckingResult *match in arrayOfAllMatches)
//    {
//        NSString* substringForMatch = [url substringWithRange:match.range];
//    }
    
    return NO;
}




/** //有问题:出来的时候,慢一点; 不能同步
 *	@brief	自定义数字键盘,在数字键盘添加完成按钮; 先遍历windows获取键盘所在的window,然后在windows遍历view获得view(UIInputSetContainerView,frame是整个windows大小)
 */

- (void)zx_keyboardToAddFinishButton
{
    // create custom button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
    //最好用2张图片替换/不然有点不混合;
    [doneButton setTitle:NSLocalizedString(@"完成", nil)  forState:UIControlStateNormal];
    [doneButton setTintColor:[UIColor blackColor]];
    
    [doneButton addTarget:self action:@selector(finishSelectedAction:) forControlEvents:UIControlEventTouchUpInside];
    
    __block UIWindow* keyboardWindow = nil;
    NSArray* windows = [[UIApplication sharedApplication] windows];
    [windows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *str =  [[obj class] description];
        if ([str isEqualToString:@"UIRemoteKeyboardWindow"])
        {
            keyboardWindow = (UIWindow *)obj;
        }
    }];
    
    
    [[keyboardWindow subviews] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *str =  [[obj class] description];
        if ([str isEqualToString:@"UIInputSetContainerView"]||[str isEqualToString:@"UIPeripheralHostView"])
        {
            UIView* containerView = (UIView *)obj;
            [containerView addSubview:doneButton];
            
            [UIView animateKeyframesWithDuration:0.2f delay:0.f options:UIViewKeyframeAnimationOptionLayoutSubviews  animations:^{
                if (__IPHONE_8_0)
                {
                    doneButton.frame = CGRectMake(0, CGRectGetMaxY(containerView.frame)-53, 106, 53);
                }
                else
                {
                    doneButton.frame = CGRectMake(0, 163, 106, 53);
                }
                
                
            } completion:nil];
            
            
        }
    }];
    
}


- (void)finishSelectedAction:(UIButton *)sender
{
    [sender removeFromSuperview];
    [self resignFirstResponder];
}


@end
